//
//  LXLocationAwaken.m
//  LXLocationRelated
//
//  Created by Livespro on 2017/10/22.
//  Copyright © 2017年 Livesxu. All rights reserved.
//

#import "LXLocationAwaken.h"

#import "LXHandleDatas.h"

#define kLocationAwakenNoti @"LocationAwakenNotification"

@interface LXLocationAwaken ()<CLLocationManagerDelegate>

@property (nonatomic, assign) BOOL isStart;

@end

@implementation LXLocationAwaken

+ (instancetype)shareLocation{
    
    static LXLocationAwaken *location = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        location = [[LXLocationAwaken alloc]init];
        
    });
    return location;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (CLLocationManager *)locationM{
    
    if (!_locationM) {
        
        _locationM = [[CLLocationManager alloc] init];
        _locationM.delegate = self;
        
        // 设置每隔多远定位一次(1次  111km/100m)
        // 最新的位置距离上一次位置之间的距离大于10m, 才会通过代理告诉外界
        _locationM.distanceFilter = kCLDistanceFilterNone;
        
        //生成新的标题事件所需的最小角度变化(以度为单位)
//        _locationM.headingFilter = 1;
        
        // 定位精确度
        // 定位精确度越高, 越耗电, 而且, 定位时间越长
        _locationM.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        
        _locationM.pausesLocationUpdatesAutomatically = NO;
        
        _locationM.activityType = CLActivityTypeAutomotiveNavigation;
        
        if([_locationM respondsToSelector:@selector(requestAlwaysAuthorization)]){
            [_locationM requestAlwaysAuthorization];
        }
        if ([_locationM respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationM requestWhenInUseAuthorization];
        }
        if ([_locationM respondsToSelector:@selector(allowsBackgroundLocationUpdates)]) {
            _locationM.allowsBackgroundLocationUpdates = YES;
        }
    }
    return _locationM;
}

- (void)startUpdating {
    self.isStart = YES;
    
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self locationM];
    } else {
        [self.locationM setDelegate:self];
        
        if ([CLLocationManager significantLocationChangeMonitoringAvailable]) {
            [self.locationM startMonitoringSignificantLocationChanges];
        }
    }
}

- (void)stopUpdating {
    self.isStart = NO;
    
    [_locationM setDelegate:nil];
    
    [_locationM stopUpdatingLocation];
    
    if ([CLLocationManager significantLocationChangeMonitoringAvailable]) {
        [_locationM stopMonitoringSignificantLocationChanges];
    }
    _locationM = nil;
}

#pragma mark - CLLocationManagerDelegate
// 1.告诉代理可以使用新的位置数据
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations;{
    
    [[LXHandleDatas shareHandle] handleMonitorIn:[NSString stringWithFormat:@"唤醒 - %@%@",NSStringFromClass([self class]),NSStringFromSelector(_cmd)] Time:[NSDate date] User:@"01"];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kLocationAwakenNoti object:nil];
}

// 2.告诉代理位置管理者无法检索位置的值
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;{
    
}

// 3.告诉代理,更新将不再被推迟
- (void)locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error;{
    
}

// 4.告诉代理可以使用新的位置的值
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;{
    
}

// 5.告诉代理,位置更新已暂停
- (void)locationManagerDidPauseLocationUpdates:(CLLocationManager *)manager;{
    
}

// 6.告诉代理,已经恢复位置更新的交付
- (void)locationManagerDidResumeLocationUpdates:(CLLocationManager *)manager;{
    
}

// 7.告诉代理位置管理者接收到更新的标题信息
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading;{
    
    
}

//8.程序更改了授权状态
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    //针对未鉴权情况
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        //8.0及其以上，请求权限方式
        if ([manager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [manager requestAlwaysAuthorization];
        } else {//8.0以下，直接由定位触发鉴权
            [manager startUpdatingLocation];
        }
        return;
    }
    
    //拥有访问权限
    if (status == kCLAuthorizationStatusAuthorized
        || status == kCLAuthorizationStatusAuthorizedWhenInUse
        || status == kCLAuthorizationStatusAuthorizedAlways) {
        if (self.isStart == YES) {
            //如果需要启用位置
            if ([CLLocationManager significantLocationChangeMonitoringAvailable]) {
                [manager startMonitoringSignificantLocationChanges];
            }
        }
        return;
    }
    
    //位置服务不可用(待定)
    //    if ([self isDelegateValidForSelector:@selector(locationCollectionLocationServiceDidBecomeDenied:)]) {
    //        [self.delegate locationCollectionLocationServiceDidBecomeDenied:self];
    //    }
}


@end
